package com.taomus.mytools.other.utils;

import org.springframework.cglib.core.ReflectUtils;

import com.taomus.mytools.lang.exception.GetClassException;
import com.taomus.mytools.lang.exception.InstanceException;
import com.taomus.mytools.lang.inter.IDSLang;
import com.taomus.mytools.lang.inter.IMethod;
import com.taomus.mytools.other.utils.exception.TypeException;

public final class ProxyInvoke {
	private IDSLang dslang = null;
	private String path = null;

	public ProxyInvoke() {
	}

	public ProxyInvoke(IDSLang dsl, String path) {
		this.dslang = dsl;
		this.path = path;
	}

	public Object invoke(String method,Class<?>[] params,Object...objects) throws InstanceException, GetClassException{
		Object retVal = null;
		if(this.path != null && this.dslang !=null) {
			IMethod dslMethod = this.dslang.newInstance(this.path);
			retVal = dslMethod.getMethod(method).invoke(objects);
		}
		return retVal;
	}
	
	public Object defualtInvoke(Class<?> defualtZlass, String method, Class<?>[] params, Object... objects)
			throws Exception {
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				Object p1 = objects[i];
				Class<?> zlass = params[i];
				if (!p1.getClass().equals(zlass)) {
					throw new TypeException("The actual parameter type does not match the type definition.");
				}
			}
		}
		Object retVal = null;
		if (this.path != null && this.dslang != null) {
			retVal = this.invoke(method, params, objects);
		} else {
			Object obj = defualtZlass.newInstance();
			retVal = ReflectUtils.findDeclaredMethod(defualtZlass, method, params).invoke(obj, objects);
		}
		return retVal;
	}
}
